import home from './pages/home'
import about from './pages/about'
import article from './pages/article'
import archive from './pages/archive'
import apply from './pages/apply'
import question from "./pages/question";
import search from "./pages/search.vue"
import login from "./pages/login";
import Router from 'vue-router'
import store from "./store";
import register from "./pages/register";
import testPage from "./pages/testPage";
import forkedquestion from "./pages/forkedquestion";
import myquestion from "./pages/myquestion";
import storage from "./model/storage";
const routes = [{
        path: '/',
        component: home
    },
    {
        path: '/home',
        name: 'home',
        component: home
    },
    {
        path: '/about',
        name: 'about',
        component: about
    },
    {
        path: '/archive',
        name: 'archive',
        component: archive
    },
    {
        path: '/tag/:name',
        name: 'tag',
        component: archive
    },
    {
        path: '/article:id',
        name: 'article',
        component: article
    },
    {
        path: '/apply',
        name: 'apply',
        component: apply
    },
    {
        path: '*',
        redirect: '/'
    },
    {
        path: '/myquestion',
        name: 'myquestion',
        component: myquestion
    },
    {
        path: '/test',
        name: 'test',
        component: testPage
    },
    {
        path: '/question',
        name: 'question',
        component: question,
        // 某些页面规定必须登录后才能查看 ，可以在router中配置meta，将需要登录的requireAuth设为true，
        meta: {
            requireAuth: true,
        }

    },
    {
        path: '/register',
        name: 'register',
        component: register
    },
    {
        path: '/login',
        name: 'login',
        component: login
    },
    {
        path: '/forkedQuestion',
        name: 'forkedQuestion',
        component: forkedquestion,
        // 某些页面规定必须登录后才能查看 ，可以在router中配置meta，将需要登录的requireAuth设为true，
        meta: {
            requireAuth: true,
        }
    },
    {
        path: '/search',
        name: 'search',
        component: search
    }
]
const router = new Router({
    routes: routes
})
// 设置路由守卫，在进页面之前，判断有token，才进入页面，否则返回登录页面
if (storage.get("token")) {
    store.commit("set_token", storage.get("token"));
}
router.beforeEach((to, from, next) => {
    // 判断要去的路由有没有requiresAuth
    // to.matched.some(r => r.meta.requireAuth) or to.meta.requiresAuth
    if (to.matched.some(r => r.meta.requireAuth)) {
        if (store.state.token) {
            next(); //有token,进行request请求，后台还会验证token
        } else {
            next({
                path: "/login",
                // 将刚刚要去的路由path（却无权限）作为参数，方便登录成功后直接跳转到该路由，这要进一步在登陆页面判断
                query: {
                    redirect: to.fullPath
                }
            });
        }
    } else {
        next(); //如果无需token,那么随它去吧
    }
});

export default router;